// pages/anli/anli.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selected: false,
    menuLeft: 0,
    menu: [],
    menuIndex: 0,
    page: 1,
    more: true,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.onPullDownRefresh();
  },


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const menuIndex = this.data.menuIndex;
    wx.$model.home.categories().then((res) => {
      const data = res.data;
      if (!data.length) {
        this.setData({
          menu: [],
        });
        return null;
      }

      if (!data[menuIndex]) {
        menuIndex = 0;
      }

      this.setData({
        menu: data,
        menuIndex: menuIndex,
      });

      return wx.$model.home.posts({
        only_home: 0,
        cid: data[menuIndex] ? data[menuIndex].id : 0
      });
    }).then((res) => {
      if (!res) {
        return;
      }

      this.setData({
        posts: res.data
      });
    }).finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (!this.data.more) {
      return;
    }

    const data = this.data.menu;
    const menuIndex = this.data.menuIndex;
    return wx.$model.home.posts({
      only_home: 0,
      cid: data[menuIndex] ? data[menuIndex].id : 0,
      page: this.data.page + 1,
    }).then((res) => {
      if (!res) {
        return;
      }

      this.data.page = this.data.page + 1;
      const orgData = this.data.posts;
      this.setData({
        posts: orgData.concat(res.data),
        more: res.data.length <= res.per_page
      });
    });
  },

  go_detail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/detail/index?id=' + id,
    })
  },

  /**
   * 点击菜单按钮事件
   */
  tabClick: function (e) {
    const dataset = e.currentTarget.dataset,
      index = dataset.index,
      left = e.currentTarget.offsetLeft;

    this.setData({
      menuLeft: left - 100,
      menuIndex: index
    }, () => {
      this.onPullDownRefresh();
    });
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 用户点击右上角分享朋友圈
   */
  onShareTimeline: function () {
    return this.onShareAppMessage();
  },
})